#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"

using namespace std;

static void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "serverip serverport\n"
              << std::endl;
}


int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    string serverip = string(argv[1]);
    uint16_t serverport = atoi(argv[2]);

    // 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "create socket error" << endl;
        exit(SOCKET_ERR);
    }

    // 连接
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    int cnt = 5;
    while (connect(sock, (sockaddr *)&server, sizeof(server)))
    {
        cout << "正在重连，还有" << cnt-- << "次" << endl;
        sleep(1);
        if (cnt <= 0)
            break;
    }

    if (cnt <= 0)
    {
        cout << "连接失败..." << endl;
        exit(CONNECT_ERR);
    }

    // 连接成功
    while (true)
    {
        string line;
        cout << "Please Enter# ";
        getline(cin, line);
        write(sock,line.c_str(),line.size());

        char buffer[1024];
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = '\0';
            cout << "server echo " << buffer << endl;
        }
        else if (s == 0)
        {
            cerr << "server quit" << endl;
            break;
        }
        else
        {
            cerr << "read error" << strerror(errno) << endl;
            break;
        }
    }
    close(sock);
    return 0;
}